package fm.admin.controller;

import com.alibaba.fastjson.JSON;
import fm.controller.FileUploadController;
import fm.exception.BizException;
import fm.listener.FileUploadProgressListener;
import fm.mongoService.UserService;
import fm.util.CommonUtils;
import fm.util.PoiExcelUtil;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.ShopMgrService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 61741 on 2018/1/8.
 */
@Controller
@RequestMapping("/user/upload")
public class UserUploadController extends FileUploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserUploadController.class);
    @Autowired
    HttpSession session;
    @Autowired
    fm.mongoService.UserService mongoUserService;
    @Autowired
    ShopMgrService shopMgrService;
    //文件大小限制
    private static int MAX_UPLOAD_SIZE = 1024 * 1024 * 1024;
    //默认文件类型保存目录
    private static String SAVE_PATH = "Images";
    //文件上传地址
    private static final String UPLOAD_PATH = "/resources/upload";
    @Autowired
    private FileUploadProgressListener fileUploadProgressListener;
    @Autowired
    UserService userService;

    @ResponseBody
    @RequestMapping(value = "/upexcel/{usertype}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map getExcelInfo(HttpServletResponse response, HttpServletRequest request, @PathVariable(value = "usertype") Integer userType , ModelMap modelMap) throws Exception {
        Map data = new HashMap();
        LOGGER.info("=======开始上传文件=======");
        SAVE_PATH="excel";
        try {
            Map params = new HashMap();
            FileItem fileItem = null;
            String absolutePath;
            String fileUri;

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setProgressListener(fileUploadProgressListener);
            upload.setFileSizeMax(MAX_UPLOAD_SIZE);
            List<FileItem> items = upload.parseRequest(request);
            if (items.size() <= 0) {
                throw new BizException("未找到要上传的文件，请选择文件");
            }
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //普通文本类型
                    params.put(item.getFieldName(), item.getString());
                } else {
                    //文件类型
                    fileItem = item;
                }
            }
            //放在循环之外，只获取最后一个文件
            if (fileItem == null) {
                throw new BizException("未找到要上传的文件");
            } else {
                //获取文件名
                String originalName = fileItem.getName();
                //根据时间生成新的随机文件名
                final String fileName = getSaveFileName(originalName);
                //存储路径，默认为Images
                String savePath = SAVE_PATH;
                //获取存储文件夹的绝对路径，不存在就创建一个新的文件夹
                final String realPath = getFolder(request, savePath);
                //返回路径：返回一个全局的路径
                absolutePath = realPath + "/" + fileName;
                //文件存储的相对路径
                fileUri = UPLOAD_PATH + "/" + SAVE_PATH + "/" + fileName;
                String fileUrl = fullPathBuilder(fileUri, request, response);
                //写出文件到硬盘
                fileItem.write(new File(absolutePath));
                LOGGER.info("【上传文件】文件保存绝对路径： {} \r\n 文件URL： {}", absolutePath, fileUrl);
                data.put("url", fileUrl);
                data.put("title", "");
                data.put("original", "");
                this.success(data);
                LOGGER.info("=======准备解析文件=======");
                List<Map<String,Object>> list = PoiExcelUtil.readExcelToListMap(absolutePath);
                LOGGER.info("=======插入数据=======");
                mongoUserService.insertUserbyExcel(list,userType);
            }
        } catch (BizException ex) {
            LOGGER.error("occur error in file upload : {}", ex.getMessage());
            data.put("state", "上传失败");
            this.failed(data, ex);
        } catch (Exception ex) {
            LOGGER.error("occur error in file upload : {}", ex);
            data.put("state", "上传失败");
            this.failed(data, "serve error!");
        }
        String responseData = JSON.toJSONString(data);
        LOGGER.debug("【上传文件-结束】文件信息:{}", responseData);
        return data;
    }

    /**
     * 上传物流报价单
     * @param response
     * @param request
     * @param user_id
     * @param modelMap
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/uplogexcel/{user_id}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map updatLogExcel(HttpServletResponse response, HttpServletRequest request, @PathVariable(value = "user_id") String user_id , ModelMap modelMap) throws Exception {
        Map data = new HashMap();
        LOGGER.info("=======开始上传文件=======");
        SAVE_PATH="excel";
        if(CommonUtils.isEmpty(user_id)){
            throw new BizException("请输入用户id!");
        }
        try {
            Map params = new HashMap();
            FileItem fileItem = null;
            String absolutePath;
            String fileUri;

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setProgressListener(fileUploadProgressListener);
            upload.setFileSizeMax(MAX_UPLOAD_SIZE);
            List<FileItem> items = upload.parseRequest(request);
            if (items.size() <= 0) {
                throw new BizException("未找到要上传的文件，请选择文件");
            }
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //普通文本类型
                    params.put(item.getFieldName(), item.getString());
                } else {
                    //文件类型
                    fileItem = item;
                }
            }
            //放在循环之外，只获取最后一个文件
            if (fileItem == null) {
                throw new BizException("未找到要上传的文件");
            } else {
                //获取文件名
                String originalName = fileItem.getName();
                //根据时间生成新的随机文件名
                final String fileName = getSaveFileName(originalName);
                //存储路径，默认为Images
                String savePath = SAVE_PATH;
                //获取存储文件夹的绝对路径，不存在就创建一个新的文件夹
                final String realPath = getFolder(request, savePath);
                //返回路径：返回一个全局的路径
                absolutePath = realPath + "/" + fileName;
                //文件存储的相对路径
                fileUri = UPLOAD_PATH + "/" + SAVE_PATH + "/" + fileName;
                String fileUrl = fullPathBuilder(fileUri, request, response);
                //写出文件到硬盘
                fileItem.write(new File(absolutePath));
                LOGGER.info("【上传文件】文件保存绝对路径： {} \r\n 文件URL： {}", absolutePath, fileUrl);
                data.put("url", fileUrl);
                data.put("title", "");
                data.put("original", "");
                this.success(data);
                List<Map<String,Object>> list = PoiExcelUtil.readExcelToListMap(absolutePath);
                shopMgrService.getLogPriceInfoByExcel(list,user_id);
            }
        } catch (BizException ex) {
            LOGGER.error("occur error in file upload : {}", ex.getMessage());
            data.put("state", "上传失败");
            this.failed(data, ex);
        } catch (Exception ex) {
            LOGGER.error("occur error in file upload : {}", ex);
            data.put("state", "上传失败");
            this.failed(data, "serve error!");
        }
        String responseData = JSON.toJSONString(data);
        LOGGER.debug("【上传文件-结束】文件信息:{}", responseData);
        return data;
    }
}
